package com.wanqing.community.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * 字符串辅助类
 */
public class StringTools {
	
	private static Logger log = Logger.getLogger(StringTools.class);

	/**
	 * 去掉字符串最后的指定字符串
	 * 
	 * @param sourceString
	 *            要截取的源字符串
	 * @param targetString
	 *            指定字符串
	 * @return
	 */
	public static String removeLastString(String sourceString,
			String targetString) {
		if (isEmptyOrNull(sourceString)) {
			return "";
		} else {
			int index = sourceString.lastIndexOf(targetString);
			return sourceString.substring(0, index);
		}
	}

	/**
	 * 把一个Object转化成字符串
	 * 
	 * @param obj
	 * @return
	 */
	public static String objectToString(Object obj) {
		if(isEmptyOrNull(obj)){
			return "";
		}
		return String.valueOf(obj).trim();
	}
	
	/**
	 * 判断Object是否为空或null
	 * @param obj
	 * @return
	 */
	public static boolean isEmptyOrNull(Object obj){
		if(null==obj){
			return true;
		}
		String temp = String.valueOf(obj).trim();
		return isEmptyOrNull(temp);
	}
	
	/**
	 * <p>Description:<p>
	 * <p>modifiContent:<p>
	 * @param source
	 * @return
	 */
	public static boolean isNotEmptyOrNull(String source) {		
		return !isEmptyOrNull(source);
	}

	/**
	 * 把二个Object 比较转化成字符串
	 * 
	 * @param obj
	 * @return
	 */
	public static String objectToString(Object temobj, Object obj) {
		if (null == obj) {
			return objectToString(temobj);
		} else {
			return objectToString(obj);
		}
	}

	/**
	 * 把一个Object转化成字符串
	 * 
	 * @param obj
	 * @return
	 */
	public static String objectToString(String obj) {
		if (isEmptyOrNull(obj)) {
			return "";
		} else {
			return obj.trim();
		}
	}
	

	/**
	 * 判断两个字符串是否相等
	 * 
	 * @param str1
	 * @param str2
	 * @return
	 */
	public static boolean decideString(String str1, String str2) {
		boolean result = false;
		String tempstr1 = objectToString(str1);
		String tempstr2 = objectToString(str2);
		result = tempstr1.equals(tempstr2);
		return result;
	}

	/**
	 * 取字符串第index上的字符串
	 * 
	 * @param sourceString
	 * @param index
	 * @return
	 */
	public static String interceptStr(String sourceString, int index) {
		if (StringTools.isEmptyOrNull(sourceString)) {
			return "0";
		}
		String tempstr1 = objectToString(sourceString);
		return String.valueOf(tempstr1.charAt(index));
	}

	/**
	 * 取字符串第index上的字符串并转为整形
	 * 
	 * @param sourceString
	 * @param index
	 * @return
	 */
	public static int interceptInt(String sourceString, int index) {
		if (StringTools.isEmptyOrNull(sourceString)) {
			return 0;
		}
		String tempstr1 = objectToString(sourceString);
		String temp = String.valueOf(tempstr1.charAt(index));
		return NumberDealTools.stringTranceInt(temp);
	}

	/**
	 * 验证字符串中的某一段是否全为0
	 * 
	 * @param sourceString
	 * @param index
	 * @param end
	 * @return
	 */
	public static boolean checkStringZ(String sourceString, int index, int end) {
		if (StringTools.isEmptyOrNull(sourceString)) {
			return true;
		}
		String regex = "^[0]*$";
		String tempstr = objectToString(sourceString);
		String temp = tempstr.substring(index, end + 1);
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(temp);
		return m.matches();
	}

	/**
	 * 把一个Object转化成字符串 如果obj为空或null,"" 则返回 defaultval
	 * 
	 * @param obj
	 * @param defaultval
	 * @return
	 */
	public static String objectToString(String obj, String defaultval) {
		if(StringTools.isEmptyOrNull(obj)){
			return defaultval;
		}else{
			return obj.trim();
		}
	}

	/**
	 * 验证IP地址的格式是否合法
	 * 
	 * @param ip
	 * @return
	 */
	public static boolean regxStringOfIp(String ip) {
		String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(ip);
		return m.matches();
	}

	/**
	 * 验证字符串是否是字母或数字且只能以字母或下划线开头
	 * 
	 * @param source
	 * @return
	 */
	public static boolean regexLettOrNum(String source) {
		String regex = "^([a-zA-Z_]{1})([\\w]*)$";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(source);
		return m.matches();
	}

	/**
	 * 验证字符串是否全是数字
	 * 
	 * @param source
	 * @return
	 */
	public static boolean regexNumber(String source) {
		Pattern p = Pattern.compile("\\d+");
		Matcher m = p.matcher(source);
		return m.matches();
	}

	/**
	 * 组织权限串时使用 如果source为空则返0
	 * 
	 * @param source
	 * @return
	 */
	public static String authString(String source) {
		if (isEmptyOrNull(source)) {
			return "0";
		} else {
			return source;
		}
	}
	
	/**
	 * <p>Description:将字符串，以第index位分割成一个长度为2的一维数组<p>
	 * <p>modifiContent:<p>
	 * @param source
	 * @param index
	 * @return
	 */
	public static String[] split(String source,int index){
		String[] str = new String[2];
		if(isEmptyOrNull(source)){
			str[0] = "";
			str[1] = "";
		}else{
			int len = source.length();
			str[0] = source.substring(0, len-index);
			str[1] = source.substring(len-index, len);
		}
		return str;
	}
	
	/**
	 * <p>Description:将字符串source以separatorChars分割成数组,如果source为空或空串则返回null,<br/>
	 * 请使用此方法分割字符串，尽量少用String的split方法，String的split方法是以正则表达式的形式来分割，效率低于此方法
	 * <p>
	 * <p>modifiContent:<p>
	 * @param source
	 * @param separatorChars
	 * @return
	 */
	public static String[] split(String source,String separatorChars){
		if(isEmptyOrNull(source)){
			return null;
		}
		if(!source.contains(separatorChars)){
			return new String[]{source};
		}else{
			return StringUtils.split(source, separatorChars);
		}		
	}

	/**
	 * 取一个字符串中指定位置上的字符串
	 * 
	 * @param source
	 * @param index
	 * @return
	 */
	public static String getIndexString(String source, int index) {
		if (null == source || "".equals(source.trim())) {
			return "0";
		} else {
			return String.valueOf(source.charAt(index));
		}
	}

	/**
	 * 取字符串中指定位置上的整型数
	 * 
	 * @param source
	 * @param index
	 * @return
	 */
	public static int getIndexInt(String source, int index) {
		String temp = getIndexString(source, index);
		return Integer.parseInt(temp);
	}

	/**
	 * Clob转为String型
	 * 
	 * @param clob
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 */
	public static String clobToString(Clob clob) throws SQLException {
		if (null == clob) {
			return "";
		} else {
			try {
				Reader reader = clob.getCharacterStream();
				BufferedReader br = new BufferedReader(reader, 1024 * 20);
				StringBuffer sb = new StringBuffer();
				String str = br.readLine();
				while (null != str) {
					sb.append(str);
					str = br.readLine();
				}
				return sb.toString();
			} catch (IOException e) {
				return "";
			}
		}
	}

	/**
	 * 去掉字符串中的html标记
	 * 
	 * @param source
	 * @return
	 */
	public static String removeHtmlFlag(String source) {
		if (null == source || "".equals(source.trim())) {
			return "";
		} else {
			return source.replaceAll("</?[^>]+>", "");
		}
	}

	/**
	 * 中文字符串url转码
	 * 
	 * @param source
	 * @param code
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String strEncode(String source, String code){
		if (null == source || "".equals(source) || "null".equals(source)) {
			return "null";
		} else {
			try {
				return URLEncoder.encode(source, code);
			} catch (UnsupportedEncodingException e) {				
				log.error(e.toString());
			}
		}
		return "";
	}

	/**
	 * 中文字符串url转码
	 * 
	 * @param source
	 * @param code
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String strEncode(String source){
		if (null == source || "".equals(source) || "null".equals(source)) {
			return "";
		} else {
			try {
				return URLEncoder.encode(source.trim(), "UTF-8");
			} catch (UnsupportedEncodingException e) {				
				log.error(e.toString());
			}
		}
		return "";
	}

	/**
	 * 中文字符串URL解码
	 * 
	 * @param source
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String strDencode(String source){			
		if (isEmptyOrNull(source)) {
			return "";
		} else {
			try {
				return URLDecoder.decode(source.trim(), "UTF-8");
			} catch (UnsupportedEncodingException e) {				
				log.error(e.toString());
			}
		}
		return "";
	}

	/**
	 * 验证是否为整数或者有2位小数的数
	 * 
	 * @param source
	 * @return
	 */
	public static boolean checkTwoFloat(String source) {
		if (null == source || "".equals(source.trim())) {
			return false;
		} else {
			String regex = "^[1-9]+\\d*[\\.\\d]?\\d{0,2}$";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(source);
			return m.matches();
		}
	}

	/**
	 * 判断是否存在空格
	 * 
	 * @param source
	 * @return
	 */
	public static boolean checkSpace(String source) {
		if (StringTools.isEmptyOrNull(source)) {
			return false;
		}
		if (source.contains(" ")) {
			return true;
		}
		return false;
	}

	/**
	 * IP转为long
	 * 
	 * @param strIp
	 * @return
	 */
	public static long ipToLong(String strIp) {
		String[] ip = strIp.split("\\.");
		long a0 = Long.parseLong(ip[0]);// 第一位
		long a1 = Long.parseLong(ip[1]);// 第二位
		long a2 = Long.parseLong(ip[2]);// 第三位
		long a3 = Long.parseLong(ip[3]);// 第四位
		long result = (a0 << 24) + (a1 << 16) + (a2 << 8) + a3;
		return result;
	}		

	/**
	 * 判断字符串是否是由reg开始，若是则用rep替换
	 * @param source
	 * @param reg
	 * @param rep
	 * @return
	 */
	public static String repale(String source, String reg, String rep) {
		String result = "";
		if (null == source || "".equals(source.trim())) {
			result = "";
		} else {
			if (source.trim().startsWith(reg)) {
				result = source.replaceFirst(reg, rep);
			} else {
				result = source;
			}
		}
		return result;
	}

	/**
	 * 判断字符串是否为null或者""
	 * 
	 * @author 杨洪超
	 * @param source
	 *            要判断的字符串
	 * @return
	 */
	public static boolean isEmpty(String source) {
		return StringUtils.isEmpty(source);
	}

	/**
	 * 判断字符串是否为null或者""或者"null"
	 * 如果字符串为空或null,"","NULL","null"返回true 否则返回false
	 * @param source
	 * @return
	 */
	public static boolean isEmptyOrNull(String source) {
		return StringUtils.isEmpty(source) || ("null".equalsIgnoreCase(source) || ("undefined".equalsIgnoreCase(source)));
	}

	/**
	 * 判断两个字符串的大小 start>end 1,start<end -1,start=end 0
	 * 
	 * @param start
	 * @param end
	 * @return start>end 1,start<end -1,start=end 0
	 */
	public static int checkTwoString(String start, String end) {
		return start.compareToIgnoreCase(end);
	}

	/**
	 * 将字符串source最后的big位字符串替换为target
	 * 
	 * @param source
	 * @param big
	 * @param target
	 * @return
	 */
	public static String repalce(String source, int big, String target) {
		if (null == source || "".equals(source)) {
			return "";
		} else if (source.length() < big) {
			return "";
		} else if (null == target) {
			return source;
		} else {
			int index = source.length() - big;
			String temp = source.substring(index, source.length());
			String tempValue = "";
			for (int i = 0; i < big; i++) {
				tempValue += temp.replace(temp, target);
			}
			String result = source.substring(0, index) + tempValue;
			return result;
		}
	}
	
	/**
	 * 根据当前路径得到文件扩展名
	 * 
	 * @return 扩展名
	 */
	public static String getTypes(String path) {
		String types = path.substring(path.lastIndexOf(".") + 1, path.length());
		return types;
	}

	private static final String[] TYPES = { "jpg", "gif", "jpeg" };

	/**
	 * 判断文件是否是有效文件
	 */
	public static boolean checkType(String types) {
		for (int i = 0; i < TYPES.length; i++) {
			if (types.equalsIgnoreCase(TYPES[i])) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 验证是否为整数或者小数
	 * 
	 * @param source
	 * @return
	 */
	public static boolean regexDec(String source) {
		if (null == source || "".equals(source.trim())) {
			return false;
		} else {
			String regex = "^[0-9]+([.]{1}[0-9]+?)?$";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(source);
			return m.matches();
		}
	}

	public static boolean regex4String(String source) {
		if (StringTools.isEmptyOrNull(source)) {
			return false;
		}
		String regex = "\\d{4}";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(source);
		return m.matches();
	}

	public static String authString() {
		String result = "";
		for (int i = 0; i < 450; i++) {
			result += "9";
		}
		return result;
	}

	/**
	 * 拆分字符串
	 * 
	 * @param source
	 * @param targ
	 * @return
	 */
	public static String[] teilen(String source, String targ) {
		if (null == source || null == targ) {
			return null;
		} else {
			return source.split(targ);
		}
	}

	public static String checkString(String temString, String sourString) {
		if (null == sourString || "".equals(sourString.trim())) {
			return temString.trim();
		} else {
			return sourString.trim();
		}
	}

	/**
	 * 判断targetstr是否在数组soures内中返回true
	 * 
	 * @param soures
	 * @param targetstr
	 * @return
	 */
	public static boolean checkString(String[] soures, String targetstr) {
		boolean flag = false;
		if (null == soures || StringTools.isEmptyOrNull(targetstr)) {
			return false;
		}
		for (int i = 0; i < soures.length; i++) {
			String temp = StringTools.objectToString(soures[i]);
			if (temp.equals(targetstr)) {
				flag = true;
				break;
			}
		}
		return flag;
	}

	/**
	 * 5-4日 转换html 字符串如&lt;->‘<’,&gt;->'>';
	 * 
	 * @param unescapeStr
	 *            被转换的字符串
	 * @return
	 */
	public static String unescapeHtml(String unescapeStr) {
		return StringEscapeUtils.unescapeHtml(unescapeStr);
	}

	/**
	 * 
	 * @param matcheStr
	 *            被匹配的字符串
	 * @return 匹配字符串中是否含有HTML标记
	 */
	public static boolean matcheHtml(String matcheStr) {
		return Pattern.matches("<(.*)>.*<\\/\\1>|<(.*)\\/>", matcheStr);
	}	

	/**
	 * 只显示姓名中的姓
	 * 
	 * @param s
	 * @return
	 */
	public static String displayOnlyFirstNameWild(String s) {
		if (isEmpty(s)) {
			return "";
		}
		return s.substring(0, 1) + "****";
	}
	
	public static boolean stringToBoolean(String source){
		if(isEmptyOrNull(source)){
			return false;
		}
		Boolean b = Boolean.valueOf(source);
		return b.booleanValue();
	}

	/**
	 * 隐藏银行卡后四位
	 * 
	 * @param bankCard
	 * @return
	 */
	public static String hideBankCardLastFour(String bankCard) {
		if (isEmpty(bankCard)) {
			return "";
		}
		return bankCard.substring(0, bankCard.length() - 4) + "****";
	}

	/**
	 * 验证字母、数字、下划线、短横线
	 * 
	 * @param source
	 * @return
	 */
	public static boolean checkStringNumber(String source) {
		Pattern p = Pattern.compile("[A-Za-z0-9_-]+");
		Matcher m = p.matcher(source);
		return m.matches();
	}

	/**
	 * 截取字符串的后几位
	 * 
	 * @param val
	 *            要截取的字符串
	 * @param len
	 *            截取长度
	 * @return
	 */
	public static String subStringWithBack(String val, int len) {

		if (val == null) {
			return "";
		}

		int length = val.length();

		if (length < len) {
			return val;
		}

		return val.substring(length - len);
	}

	/**
	 * <p>
	 * 判断图片格式
	 * <p>
	 * 
	 * @param imageType
	 * @return
	 */
	public static boolean checkImageType(String imageType) {
		boolean flag = false;
		if (!isEmptyOrNull(imageType)) {
			if ("image/bmp".equalsIgnoreCase(imageType.trim())
					|| "image/gif".equalsIgnoreCase(imageType.trim())
					|| "image/jpg".equals(imageType.trim())
					|| "image/x-png".equalsIgnoreCase(imageType.trim()) || "image/pjpeg".equalsIgnoreCase(imageType.trim())) {
				flag = true;
			}else{
				flag = false;
			}
		}
		return flag;
	}
	
	public static String buildJson(Object objArray,boolean replace){
		JSONArray jsonArray = JSONArray.fromObject(objArray);		
		String result = jsonArray.toString();;
		if (replace) {
			result = removeLastString(result, "]");
			result = result.replaceFirst("\\[", "");
		}
		return result;		
	}
	
	public static String buildJson(Object objArray,JsonConfig config,boolean replace){
		JSONArray jsonArray = JSONArray.fromObject(objArray, config);	
		String result = jsonArray.toString();;
		if (replace) {
			result = removeLastString(result, "]");
			result = result.replaceFirst("\\[", "");
		}
		return result;		
	}
	
	public static String buildJson(Object objArray,String[] excludes,boolean replace){
		JsonConfig confing = new JsonConfig();
		confing.setExcludes(excludes);
		JSONArray jsonArray = JSONArray.fromObject(objArray, confing);	
		String result = jsonArray.toString();;
		if (replace) {
			result = removeLastString(result, "]");
			result = result.replaceFirst("\\[", "");
		}
		return result;	
	}
	
	public static String buildJson(Object obj){
		JSONObject jsonObject = JSONObject.fromObject(obj);
		return jsonObject.toString();
	}
	
	public static String buildJson(Object obj,JsonConfig config){
		JSONObject jsonObject = JSONObject.fromObject(obj, config);
		return jsonObject.toString();
	}
	
	public static String buildJson(Object obj,String[] excludes){
		JsonConfig confing = new JsonConfig();
		confing.setExcludes(excludes);
		JSONObject jsonObject = JSONObject.fromObject(obj, confing);
		return jsonObject.toString();
	}
	
	/**
	 * 验证是否为手机号码
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNo(String mobiles){
		if(isEmptyOrNull(mobiles)){
			return false;
		}		
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}
	
	/**
	 * 验证是否为EMAIL格式
	 * @param emails
	 * @return
	 */
	public static boolean isEmail(String emails){
		if(isEmptyOrNull(emails)){
			return false;
		}
		String str="^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(emails);
		return m.matches();
	}
	
	/**
	 * 验证座机格式是否正确
	 * @param phones
	 * @return
	 */
	public static boolean isPhone(String phones){
		if(isEmptyOrNull(phones)){
			return false;
		}
		String str1 = "[0]{1}[0-9]{2,3}-[0-9]{7,8}"; 
		String str2 = "[0]{1}[0-9]{2,3}[0-9]{7,8}";
		Pattern p1 = Pattern.compile(str1);
		Matcher m1 = p1.matcher(phones);
		Pattern p2 = Pattern.compile(str2);
		Matcher m2 = p2.matcher(phones);
		return m1.matches() || m2.matches();
	}
	
	/**
	 * 
	 * <p>Description:给URL追加参数<p>
	 * <p>modifiContent:</p>
	 * @param url
	 * @param parameter
	 * @param value
	 * @return
	 */
	public static String urlAddParmert(String url, String parameter, String value){
		StringBuffer buf = new StringBuffer();
        if (!isEmptyOrNull(url)) {
            buf.append(url);
            if (url.indexOf("?") > -1){  //已经有参数            
                buf.append("&");
            } else {
                buf.append("?");
            }
            buf.append(parameter);
            buf.append("=");
            buf.append(value);
        }
        return buf.toString();
	}
	
	/**
	 * <p>Description:字符串转码<p>
	 * <p>modifiContent:<p>
	 * @param source 要转码的字符串
	 * @param orig 原编码格式
	 * @param dest 目标编码格式
	 * @return
	 */
	public static String strChangeCode(String source,String orig,String dest){
		if(isEmptyOrNull(source)){
			return "";
		}
		try {
			String temp = new String(source.getBytes(orig),dest);
			return temp;
		} catch (UnsupportedEncodingException e) {			
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * <p>Description:将字符串由ISO-8859-1转为UTF-8<p>
	 * <p>modifiContent:<p>
	 * @param source
	 * @return
	 */
	public static String strISOToUtf8(String source){
		return strChangeCode(source, "ISO-8859-1", "UTF-8");
	}
	
	/**
	 * <p>Description:将字符串由ISO-8859-1转为GB2312<p>
	 * <p>modifiContent:<p>
	 * @param source
	 * @return
	 */
	public static String strISOToGB2312(String source){
		return strChangeCode(source, "ISO-8859-1", "GB2312");
	}
	
	/**
	 * <p>Description:将字符串由Utf8转为GB2312<p>
	 * <p>modifiContent:<p>
	 * @param source
	 * @return
	 */
	public static String strUtf8ToGB2312(String source){
		return strChangeCode(source, "UTF-8", "GB2312");
	}
	
	public static Map<String, String> parserFormParam(String formParams) {
		Map<String, String> paramMap = new HashMap<String, String>();
		if (!isEmptyOrNull(formParams)) {
			String[] params = formParams.split("&");
			if (null != params && params.length > 0) {
				for (int i = 0; i < params.length; i++) {
					String[] temp = params[i].split("=");
					if (null != temp) {
						if (temp.length == 2) {
							paramMap.put(temp[0], StringTools.strDencode(temp[1]));
						}
					}
				}
			}
		}
		return paramMap;
	}
	
	/**
	 * <p>Description:格式化里程，index位小数 返回格式为  Kxxx+xxx<p>
	 * <p>modifiContent:</p>
	 * @param source
	 * @return
	 */
	public static String mileage(String source,int index){
		if(isEmptyOrNull(source)){
			return "";
		}		
		BigDecimal bd = new BigDecimal(source).setScale(index,BigDecimal.ROUND_DOWN);		
		String retStr = "K"+bd.toString().replace(".", "+");
		return retStr;
	}
	
	
	
	public static String mileage1(String source){
		if(isEmptyOrNull(source)){
			return "k0";
		}		
		if(!source.startsWith("k") && !source.startsWith("K")){
			return "K"+source;
		}		
		return source;
	}
	
	/**
	 * <p>Description:格式化里程，3位小数 返回格式为  Kxxx+xxx<p>
	 * <p>modifiContent:</p>
	 * @param source
	 * @return
	 */
	public static String mileage(double value){
		 String source = String.valueOf(value);
		 return mileage(source,3);
	}
	
	/**
	 * <p>Description:格式化里程，将整形米格式化成公里 Kxxx+xxx的表示方法<p>
	 * <p>modifiContent:<p>
	 * @param value
	 * @return
	 */
	public static String mileage(int value){
		double b = Double.parseDouble(String.valueOf(value));
		b = b/1000;
		return mileage(b);
	}
	
	/**
	 * <p>Description:格式化里程，将字符串形式的米格式化成公里 Kxxx+xxx的表示方法<p>
	 * <p>modifiContent:<p>
	 * @param value
	 * @return
	 */
	public static String mileage(String value){
		if(isEmptyOrNull(value)){
			return "";
		}
		double b = NumberDealTools.stringTranceDouble(value);
		b = b/1000;
		return mileage(b);
	}
	
	/**
	 * <p>Description:格式化里程，index位小数 返回格式为  Kxxx+xxx<p>
	 * <p>modifiContent:</p>
	 * @param source
	 * @return
	 */
	public static String mileage(double value,int index){
		 String source = String.valueOf(value);
		 return mileage(source,index);
	}
	
	/**
	 * <p>Description:将Kxxx+xxx格式的里程转换了double形的公里数据<p>
	 * <p>modifiContent:</p>
	 * @param source
	 * @return
	 */
	public static double deMileage(String source){
		if(isEmptyOrNull(source)){
			return 0.000d;
		}		
		if(source.startsWith("k") || source.startsWith("K")){
			String temp = source.substring(1).replace("+", ".");
			return NumberDealTools.stringTranceDouble(temp);	
		}else if(source.contains("+")){
			String temp = source.replace("+", ".");
			return NumberDealTools.stringTranceDouble(temp);	
		}else{
			return NumberDealTools.stringTranceDouble(source);
		}
	}
	
	/**
	 * <p>Description:将Kxxx+xxx格式的里程转换了double形的公里数据<p>
	 * <p>modifiContent:<p>
	 * @param source
	 * @param direct 表示进行前面加零（front）、后面加零(back)
	 * @return
	 */
	public static double deMileage(String source,String direct){
		double mileage = 0d;
		if("back".equalsIgnoreCase(direct)){
			mileage = deMileage(source);
		}else if("front".equalsIgnoreCase(direct)){
			String result = deMileage1(source);
			mileage = NumberDealTools.stringTranceDouble(result);
		}
		return mileage;
	}
	
	private static String deMileage1(String source){
		String result = "-1";
		if(isEmptyOrNull(source)){
			return "-1";
		}
		if(source.startsWith("k") || source.startsWith("K")){
			result = source.substring(1).replace("+", ".");
		}else if(source.contains("+")){
			result = source.replace("+", ".");
		}
		String[] temp = split(result, ".");		
		int rs = NumberDealTools.stringTranceInt(temp[1]);
		String r = NumberDealTools.format(rs, 3);
		result = temp[0]+"."+r;
		return result;
	}
	
	/**
	 * <p>Description:将Kxxx+xxx格式的里程转换为以米表示的int形数据<p>
	 * <p>modifiContent:</p>
	 * @param source
	 * @return
	 */
	public static int deMileageMetre(String source){
		if(isEmptyOrNull(source)){
			return -1;
		}
		double b = deMileage(source);
		if(b==-1d){
			return -1;
		}
		return NumberDealTools.doubleToInt(b*1000);
	}
	
	/**
	 * <p>Description:将Kxxx+xxx格式的里程转换为以米表示的int形数据<p>
	 * <p>modifiContent:<p>
	 * @param source
	 * @param direct 表示进行前面加零（front）、后面加零(back)
	 * @return
	 */
	public static int deMileageMetre(String source,String direct){
		int mileage = 0;
		if("back".equalsIgnoreCase(direct)){
			mileage = deMileageMetre(source);
		}else if("front".equalsIgnoreCase(direct)){
			String result = deMileage1(source);
			double b = NumberDealTools.stringTranceDouble(result);
			if(b==-1d){
				return -1;
			}
			mileage = NumberDealTools.doubleToInt(b*1000);
		}
		return mileage;
	}
	
	/**
	 * <p>Description:获取IP地址<p>
	 * <p>modifiContent:<p>
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	/**
	 * <p>Description:将source的首字母转为大写<p>
	 * <p>modifiContent:<p>
	 * @param source
	 * @return
	 */
	public static String firstLetterUpperCase(String source){
		if(isEmptyOrNull(source)){
			return "";
		}
		byte[] items = source.getBytes();  
		items[0] = (byte) ((char) items[0] - 'a' + 'A');  
		return new String(items);  
	}
	
	/**
	 * <p>Description:将行别转为标准显示方式<p>
	 * <p>modifiContent:<p>
	 * @param lineType
	 * @return
	 */
	public static String getLineType(String lineType){
		if(StringTools.isEmptyOrNull(lineType)){
			return "";
		}
		String first = lineType.substring(0, 1);
		if("上".equals(first) || "下".equals(first) || "单".equals(first)){
			return first+"行"; 
		}
		return lineType;
	}
	/**
	 * <p>Description:<p>
	 * <p>modifiContent:<p>
	 * @param lineSort
	 * @return
	 */
	public static String getLineType(int lineSort){
		String lineType = "";
		if(lineSort==3){
			lineType = "单行";
		}else if(lineSort==2){
			lineType = "下行";
		}else if(lineSort==1){
			lineType = "上行";
		}else{
			lineType = "站内";
		}
		return lineType;
	}
	
	/**
	 *<p>Description:根据行别返回对应的数字编码</p>
	 * @param lineType
	 * @return
	 */
	public static int getLineTypeNo(String lineType){
		int lineTypeNo = 0;
		if("上行".equals(lineType)) {
			lineTypeNo = 1;
		} else if("单行".equals(lineType)) {
			lineTypeNo = 3;
		} else if("下行".equals(lineType)) {
			lineTypeNo = 2;
		}
		return lineTypeNo;
	}
	
	/**
	 * <p>Description:去掉空行<p>
	 * <p>modifiContent:<p>
	 * @param source
	 * @return
	 */
	public static String replaceBlank(String source){
		if(isEmptyOrNull(source)){
			return "";
		}
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(source);
		source = m.replaceAll("");
		return source;
	}
	
	/**
	 * <p>Description:将空行替换成指定的字符串<p>
	 * <p>modifiContent:<p>
	 * @param source
	 * @param replaceStr
	 * @return
	 */
	public static String replaceBlank(String source,String replaceStr){
		if(isEmptyOrNull(source)){
			return "";
		}
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(source);
		source = m.replaceAll(replaceStr);
		return source;
	}
	/**
	 * <p>Description:去掉字符串中的重复字符，每个字符以prefix分开<p>
	 * <p>modifiContent:<p>
	 * @param source
	 * @param splits
	 * @return
	 */
	public static String repetition(String source,String prefix){
		if(isEmptyOrNull(source)){
			return "";
		}
		String temp = source;
		if(temp.startsWith(prefix)){
			temp = temp.replaceFirst(prefix, "");
		}
		if(temp.endsWith(prefix)){
			temp = removeLastString(temp, ",");
		}
		String[] temps = split(source, prefix);
		if(null==temps || temps.length==0){
			return "";
		}
		Set<String> sets = new LinkedHashSet<String>();
		for (String value : temps) {
			sets.add(value);
		}
		StringBuffer sb = new StringBuffer();
		for (String string : sets) {
			sb.append(string).append(",");
		}
		return removeLastString(sb.toString(), ",");
	}
	
	public static String newRandom() {
		/*char code[] = { 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4',
				'5', '6', '7', '8', '9' };
		Random random = new Random();
		String s = "";
		for (int i = 0; i < 6; i++) {
			String strRand = String.valueOf(code[random.nextInt(code.length)]);
			s = (new StringBuilder(String.valueOf(s))).append(strRand)
					.toString();
		}
		return s;*/
		String[] randomColor = new String[] {   
	            "AFD8F8", "F6BD0F", "8BBA00","FF8E46","008E8E","D64646",  
	            "8E468E", "588526", "B3AA00","008ED6", "9D080D", "A186BE" };
		int ai = new Random().nextInt(12);
		return randomColor[ai];
	}
	
	/**
	 * <p>Description:查找出在Map键中与seachr相似的字符串<p>
	 * <p>modifiContent:<p>
	 * @param map 
	 * @param seachr 要查找或对比的字符串
	 * @return
	 */
	protected String contain(Map<String, String> map,String seachr){
		if(null==map || map.isEmpty()){
			return seachr;
		}
		Set<String> sets = map.keySet();
		if(null==sets || sets.isEmpty()){
			return seachr;
		}
		StringBuffer sb = new StringBuffer();
		for (String key : sets) {			
			if(key.contains(seachr) || seachr.contains(key)){
				sb.append(key).append(",");
				//break;
			}
		}
		return StringTools.removeLastString(sb.toString(), ",");
	}	
	
}
